package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.oss.OssProperties;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.UUIDUtils;
import com.nineclock.message.dto.SysApplyJoinCompanyUserDTO;
import com.nineclock.message.enums.MessageTypeEnum;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.system.dto.SysChangeMainManagerDTO;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SyscompanyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SyscompanyServiceImpl implements SyscompanyService {
    @Autowired
    SysCompanyMapper sysCompanyMapper;
    @Autowired
    SysCompanyUserMapper sysCompanyUserMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SysCompanyUserRoleMapper sysCompanyUserRoleMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SmsServiceImpl smsService;
    @Autowired
    SysUserMapper userMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public SysCompanyDTO queryCompanyInfo() {
        //获取企业id
        UserInfo userInfo = CurrentUserHolder.get();
        Long companyId = userInfo.getCompanyId();

        SysCompany sysCompany = sysCompanyMapper.selectById(companyId);
        if (sysCompany == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        return BeanHelper.copyProperties(sysCompany, SysCompanyDTO.class);
    }


    @Autowired
    OSS oss;
    @Autowired
    OssProperties ossProperties;
    @Override
    public String uploadOSS(MultipartFile file) throws IOException {
        //健壮性判断
        //判断类型是否符合
        String contentType = file.getContentType();
        if (!NcConstant.ALLOWED_IMG_TYPES.contains(contentType)) {
            throw new NcException(ResponseEnum.INVALID_FILE_TYPE);
        }
        //判断文件大小
        long size = file.getSize();
        if (NcConstant.maxFileSize < size) {
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }

        //生成一个唯一的文件名称
        String uuid = UUIDUtils.getUUID();
        String oldname = file.getOriginalFilename();   //获取原始文件名
        String substring = oldname.substring(oldname.lastIndexOf("."));
        String newname = uuid + substring;
        oss.putObject(ossProperties.getBucketName(), newname, file.getInputStream());
        String format = String.format(ossProperties.getHost(), ossProperties.getBucketName()) + newname;
        //System.err.println("============================"+format);
        return format;
    }


    @Override
    public void updateCompanyInfo(SysCompanyDTO sysCompanyDTO) {
        //健壮性判断
        if (sysCompanyDTO == null || sysCompanyDTO.getName() == null || sysCompanyDTO.getLogo() == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取当前企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //查询企业信息
        SysCompany sysCompany = sysCompanyMapper.selectById(companyId);
        if (sysCompany == null) {
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        sysCompany.setName(sysCompanyDTO.getName());
        sysCompany.setLogo(sysCompanyDTO.getLogo());

        sysCompanyMapper.updateById(sysCompany);

    }


    @Override
    public void changeSysAdmin(SysChangeMainManagerDTO sysChangeMainManagerDTO) {
        //健壮性判断
        //1. 参数非空判断
        if (sysChangeMainManagerDTO == null || sysChangeMainManagerDTO.getCode() == null || sysChangeMainManagerDTO.getUserId() ==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //2. 新管理员的数据是否存在       -----------新管理员id------------------
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.selectById(sysChangeMainManagerDTO.getUserId());
        if (sysCompanyUser == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        //3. 验证码校验
        //redis中获取
        boolean b = smsService.verifySmsCode(sysCompanyUser.getMobile(), SMSConstant.SMS_TYPE_CHANGE_MANAGER, sysChangeMainManagerDTO.getCode());
        if (!b){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }


        //-------------企业id-----------------
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //--------------rode id---------------------
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getCompanyId, companyId);
        wrapper.eq(SysRole::getRoleName, "ROLE_ADMIN_SYS");
        SysRole role = sysRoleMapper.selectOne(wrapper);


        //4. 先删除
        LambdaQueryWrapper<SysCompanyUserRole> wrapper01 = new LambdaQueryWrapper<>();
        wrapper01.eq(SysCompanyUserRole::getCompanyId, companyId);
        wrapper01.eq(SysCompanyUserRole::getRoleId, role.getId());
        sysCompanyUserRoleMapper.delete(wrapper01);

        //5. 添加
        SysCompanyUserRole sysCompanyUserRole = new SysCompanyUserRole();
        sysCompanyUserRole.setCompanyId(companyId);
        sysCompanyUserRole.setCompanyUserId(sysCompanyUser.getId());
        sysCompanyUserRole.setRoleId(role.getId());
        sysCompanyUserRoleMapper.insert(sysCompanyUserRole);


    }

    @Override
    public List<SysCompanyDTO> queryCompanyByName(String keyword) {
        //健壮性判断
        if (StrUtil.isEmpty(keyword)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //,模糊查询 企业名称
        LambdaQueryWrapper<SysCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(SysCompany::getName,keyword);
        List<SysCompany> sysCompanies = sysCompanyMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(sysCompanies)){
            //企业不存在,  进行所有企业回显
            LambdaQueryWrapper<SysCompany> wrapper01 = new LambdaQueryWrapper<>();
            List<SysCompany> sysCompanies1 = sysCompanyMapper.selectList(wrapper01);
            //throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
            return  BeanHelper.copyWithCollection(sysCompanies1,SysCompanyDTO.class);
        }
        return BeanHelper.copyWithCollection(sysCompanies,SysCompanyDTO.class);
    }

    @Override
    public void applyJoinCompany(SysApplyJoinCompanyUserDTO sysApplyJoinCompanyUserDTO) {
        //健壮性判断
        if (sysApplyJoinCompanyUserDTO == null || sysApplyJoinCompanyUserDTO.getUserId() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //更新用户信息
        SysUser sysUser = userMapper.selectById(sysApplyJoinCompanyUserDTO.getUserId());
        if (sysUser == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        sysUser.setUsername(sysApplyJoinCompanyUserDTO.getUserName());
        sysUser.setLastLoginCompanyId(sysApplyJoinCompanyUserDTO.getCompanyId());
        userMapper.updateById(sysUser);

        //添加 员工信息    携带企业id说明在做申请加入企业操作
        if (sysApplyJoinCompanyUserDTO.getCompanyId() != null){
            SysCompanyUser sysCompanyUser = new SysCompanyUser();
            sysCompanyUser.setCompanyId(sysApplyJoinCompanyUserDTO.getCompanyId());
            sysCompanyUser.setCompanyName(sysApplyJoinCompanyUserDTO.getCompanyName());
            sysCompanyUser.setEnable((short)0);
            sysCompanyUser.setImageUrl(sysApplyJoinCompanyUserDTO.getImageUrl());
            sysCompanyUser.setMobile(sysApplyJoinCompanyUserDTO.getMobile());
            sysCompanyUser.setEmail(sysApplyJoinCompanyUserDTO.getEmail());
            sysCompanyUser.setPost(sysApplyJoinCompanyUserDTO.getPost());
            sysCompanyUser.setUserId(sysApplyJoinCompanyUserDTO.getUserId());
            sysCompanyUserMapper.insert(sysCompanyUser);
        }


        SysCompanyUser companyUser = sysCompanyUserMapper.getCompanyUser(sysApplyJoinCompanyUserDTO.getCompanyId());

        NcMessage message = new NcMessage();
        message.setMessageType(MessageTypeEnum.COMPANY_APPLY.getType());
        message.setAudience(MessageTypeEnum.COMPANY_APPLY.getAudience());
        message.setTitle(MessageTypeEnum.COMPANY_APPLY.getTitle());

        message.setCreateTime(new Date());
        message.setCompanyId(companyUser.getCompanyId()+"");
        message.setContent(sysApplyJoinCompanyUserDTO.getUserName() + " 正在申请加入企业,请及时审批");
        message.setUseStatus(0);
        message.setTargets(Arrays.asList(companyUser.getMobile()));
        message.setApplyUserId(sysApplyJoinCompanyUserDTO.getUserId());
        message.setApplyUsername(sysApplyJoinCompanyUserDTO.getUserName());
        message.setApproveUserId(companyUser.getUserId());
        message.setApproveUsername(companyUser.getUserName());
        message.setApproveStatue(0);


        //通过mq 把消息发送到message服务  在message中通过极光推送 给管理员
        rocketMQTemplate.convertAndSend( "messagePushTopic", message);

    }


}
